from flask import Blueprint, jsonify, request,redirect
from werkzeug.security import check_password_hash,generate_password_hash
from utils.comm import get_data
from flask_mail import Mail,Message#163发邮件
from flask import current_app as app#app导包
from db import db1
import re

bp_yh = Blueprint("yh", __name__)


def send_mail(tiele,email,comment):
    mail = Mail(app)
    msg = Message(tiele,sender='qq3367812084@163.com',recipients=[email])
    msg.html = comment
    mail.send(msg)

@bp_yh.route('/zhuce', methods=['POST'])
def zhuce():
    if request.method == 'POST':
        data = get_data()
        textemail = re.match('^[a-zA-z0-9]{4,20}@163\.com$', data['email'])
        # try:
        if textemail :
            sql1 = """select * from users where email='%s'"""%data['email']
            res = db1.find_one(sql1)
            if res:
                return jsonify({"code":1001,"mes":"用户已存在"})
            else:
                sql = """insert into users values(0,'%s','%s',%d,'%s',%d)"""%(data['name'],generate_password_hash(data['password']),0,data['email'],0)
                db1.insert(sql)
                send_mail('欢迎使用163邮箱',data['email'],"欢迎使用，点击以下<a href='http://localhost:5000/yh/validEmail?email="+data['email']+"'>链接</a>验证")
                return jsonify({"code": 200})
        # except:
        #     return jsonify({"code": 10010,"mes":'服务走丢了'})

@bp_yh.route('/validEmail')
def validEmail():
    #获取email
    email = request.args.get('email')
    #更新用户表

    sql = "update users set stalt=1 where email='%s'"%(email)

    db1.insert(sql)
    return redirect('http://localhost:8888')


@bp_yh.route('/catesM')
def catesM():
    sql = """select name from cates """
    res = db1.find_all(sql)
    return jsonify({"code":200,"list":res})

import math
@bp_yh.route('/shangp')
def shangp():
    cpage = int(request.args.get('cpage'))
    page_saze = 2
    start = (cpage-1)*page_saze
    sql = """select * from courses limit %d,%d"""%(start,page_saze)
    res = db1.find_all(sql)
    sql1="""select count(*) as count from courses"""
    ress =db1.find_one(sql1)
    count = math.ceil(int(ress['count'])/page_saze)
    return jsonify({"code":200,"list":res,"count":count})


@bp_yh.route('/ceshi',methods=['GET','POST'])
def ceshi():
    if request.method == 'GET':
        where = ' where 1 = 1'
        id = request.args.get('id')
        if id:
            where = where + ' and id =' + str(id)
        name = request.args.get('name')
        if name:
            where = where + ' and name = '+"'"+name +"'"
        sql = """select * from cates """+where
        # print(sql)
        res = db1.find_one(sql)
        return jsonify({"code":200,"list":res})









